import flet as ft
from services.device_service import DeviceService
from utils.validator import validate_required, validate_date
from datetime import datetime


class LendPage:
	def __init__(self, page):
		self.page = page
		self.service = DeviceService()
		self.build()
	
	def build(self):
		# 表单控件
		self.machine_id = ft.TextField(label="机器SN号", hint_text="输入机器唯一标识", max_length=50)
		self.serial_number = ft.TextField(label="设备编号", max_length=20)
		self.device_type = ft.Dropdown(
			label="设备类型",
			options=self._get_device_types(),
			value="手机"
		)
		self.counterpart = ft.TextField(label="出借人", hint_text="输入出借人姓名")
		self.borrow_date = ft.TextField(
			label="借入日期",
			value=datetime.now().strftime("%Y-%m-%d"),
			read_only=True
		)
		self.expected_return_date = ft.TextField(
			label="预计归还日期",
			hint_text="YYYY-MM-DD"
		)
		self.notes = ft.TextField(label="备注", multiline=True)
		
		# 提交按钮
		self.submit_btn = ft.ElevatedButton(
			"提交登记",
			icon=ft.icons.SAVE,
			on_click=self.submit
		)
		
		self.view = ft.Column(
			controls=[
				ft.Text("借入登记", size=24),
				ft.Row([self.machine_id, self.serial_number]),
				self.device_type,
				ft.Row([self.counterpart, self.borrow_date]),
				ft.Row([self.expected_return_date]),
				self.notes,
				ft.Divider(),
				self.submit_btn
			],
			spacing=15,
			scroll=ft.ScrollMode.AUTO
		)
	
	def _get_device_types(self):
		# 从数据库获取设备类型
		return [ft.dropdown.Option("手机"), ft.dropdown.Option("平板"),
		        ft.dropdown.Option("手表"), ft.dropdown.Option("扫描笔")]
	
	def submit(self, e):
		try:
			# 前端验证
			required_fields = [self.machine_id, self.counterpart]
			if not validate_required(required_fields):
				raise ValueError("请填写必填字段")
			
			if not validate_date(self.expected_return_date.value):
				raise ValueError("日期格式不正确，应为YYYY-MM-DD")
			
			record = {
				"machine_id": self.machine_id.value,
				"serial_number": self.serial_number.value,
				"device_type": self.device_type.value,
				"counterpart": self.counterpart.value,
				"record_type": "借入",
				"borrow_date": self.borrow_date.value,
				"expected_return_date": self.expected_return_date.value,
				"notes": self.notes.value,
				"status": 0,
				"owner_id": "当前用户ID"  # 需要替换为实际用户系统
			}
			
			self.service.create_record(record)
			self._clear_form()
			self.page.show_snack_bar(
				ft.SnackBar(ft.Text("借入登记成功!", color=ft.colors.GREEN_200))
			)
		except Exception as ex:
			self.page.snack_bar (
				ft.SnackBar(ft.Text(f"错误: {str(ex)}", color=ft.colors.RED_200))
			)
	
	def _clear_form(self):
		self.machine_id.value = ""
		self.serial_number.value = ""
		self.counterpart.value = ""
		self.expected_return_date.value = ""
		self.notes.value = ""
		self.page.update()
